<?php
namespace User\Controller;
use Common\Controller\MemberbaseController;
class FavoriteController extends MemberbaseController {

    const ART_TABLE_NAME = 'cms_article';

    protected $userFavorite_model;

    protected function _initialize() {
        parent::_initialize();
        $this->userFavorite_model = M("UserFavorite");
    }

    /**
     * 收藏列表
     */
    public function index() {
        $user_id = x_get_user_id();
        $favorites = $this->userFavorite_model->where("user_id = $user_id")->select();
        $this->assign("favorites", $favorites);
        $this->display(":favorite");
    }

    /**
     * 添加收藏
     */
    function add() {
        $key = I('post.key');
        if ($key) {
            $article_id = I('article_id');
            if ($key == x_encrypt_password('article-'. $article_id, SELF::ART_TABLE_NAME)) {
                $user_id = x_get_user_id();
                $find_favorite = $this->userFavorite_model->where(
                    array(
                        'table_name' => SELF::ART_TABLE_NAME,
                        'object_id'  => $article_id,
                        'user_id'    => $user_id)
                )->find();

                if ($find_favorite) {
                    $this->error("亲，您已收藏过啦！", 0, 0);
                } else {
                    $data=array(
                        'user_id'    => $user_id,
                        'table_name' => SELF::ART_TABLE_NAME,
                        'object_id'  => $article_id,
                        'createtime' => time(),
                    );
                    $result = $this->userFavorite_model->add($data);
                    if ($result) {
                        $this->success("收藏成功！", 1, 1);
                    } else {
                        $this->error("收藏失败！",0,0);
                    }
                }
            } else {
                $this->error("非法操作，无合法密钥！",0,0);
            }
        } else {
            $this->error("非法操作，无密钥！",0,0);
        }
    }

    /**
     * 删除收藏
     */
    public function delete() {
        $article_id = I('get.article_id', 0, "intval");
        if (empty($article_id)) {
            $this->error('非法操作！');
        }
        $user_id = x_get_user_id();

        $result = $this->userFavorite_model->where(
            array(
                'article_id' => $article_id,
                'user_id'    => $user_id
            ))->delete();

        if($result){
            $this->success("取消收藏成功！");
        }else {
            $this->error("取消收藏失败！");
        }
    }
}
